package workflow.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.LazyValidatorForm;
import org.springside.core.web.StrutsEntityAction;

import sun.misc.BASE64Decoder;
import sysman.model.User;
import sysman.service.ISysService;
import util.IDGeneratorUtil;
import workflow.dao.ProcessDefinitionDao;
import workflow.model.ProcessDefinition;


import common.Globals;
import common.PageInfo;

//流程定义类
public class ProcessDefinitionAction extends StrutsEntityAction<ProcessDefinition, ProcessDefinitionDao> {
	
	private ProcessDefinitionDao processDefinitionDao;
	private ISysService sysService;
	
	public ProcessDefinitionDao getProcessDefinitionDao() {
		return processDefinitionDao;
	}

	public void setProcessDefinitionDao(ProcessDefinitionDao processDefinitionDao) {
		this.processDefinitionDao = processDefinitionDao;
	}

	public ISysService getSysService() {
		return sysService;
	}

	public void setSysService(ISysService sysService) {
		this.sysService = sysService;
	}

	/**
	 *列表
	 */
	@Override
	public ActionForward list(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		LazyValidatorForm lvForm = (LazyValidatorForm)form;
		PageInfo pageInfo = new PageInfo(request);
		HashMap<String, String> hm = new HashMap<String, String>();
		//TODO 组装查询条件
		
		String id = (String)lvForm.get("s_id");
		hm.put("id" ,id);
		String preId = (String)lvForm.get("s_preId");
		hm.put("preId" ,preId);
		String name = (String)lvForm.get("s_name");
		hm.put("name" ,name);
		String processXml = (String)lvForm.get("s_processXml");
		hm.put("processXml" ,processXml);
		String version = (String)lvForm.get("s_version");
		hm.put("version" ,version);
		String creator = (String)lvForm.get("s_creator");
		hm.put("creator" ,creator);
		String crtateDate = (String)lvForm.get("s_crtateDate");
		hm.put("crtateDate" ,crtateDate);
		String type = (String)lvForm.get("s_type");
		hm.put("type" ,type);

				
		List<ProcessDefinition> poList = this.processDefinitionDao.findList(hm, pageInfo);
		request.setAttribute("list", poList);
		
		return mapping.findForward(Globals.FORWARD_LIST);
	}
	
	/**
	 * 删除
	 */
	@Override
	public ActionForward delete(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		String ids = request.getParameter("ids");
		try {
			if (ids != null && !"".equals(ids.trim())) {
				if(!getEntityManager().deleteByIds(ids)){
					this.saveError(request, "message", "删除失败：存在流程实例。");
				} else {
					this.saveMessage(request, "message", "成功删除。");
				}
				// TODO 修改操作事件，参考logWrite方法要求
				//logsManager.logWrite(request, "", "操作日志", 0);
			}
		} catch (Exception e) {
			// TODO 修改操作事件，参考logWrite方法要求
			//logsManager.logWrite(request, "", "操作日志", 0);
		}
		
		return this.list(mapping, form, request, response);
	}

	
	private void buildProcessImagePath(String imageData, String fileName){
    	BASE64Decoder decoder = new BASE64Decoder(); 
		try {
			byte[] imgBytes = decoder.decodeBuffer(imageData == null ? "" : imageData);
			File decFile = new File(fileName);
			FileOutputStream ops = new FileOutputStream(decFile);
			ops.write(imgBytes, 0, imgBytes.length);
			ops.flush();
			ops.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}	

	@Override
	protected void initForm(ActionForm form, HttpServletRequest request,
			ProcessDefinition object) {	
		LazyValidatorForm lvForm = (LazyValidatorForm) form;
		
		super.initForm(form, request, object);
	}	
	
	public void getDeps(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response){
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control ", "No-cache"); 
		response.setDateHeader("Expires", 0); 
		response.setCharacterEncoding("UTF-8");
		
		String xml = "";
		String depId = request.getParameter("depId");
		
		if(depId == null || "".equals(depId) ){
			xml = this.sysService.findDeps();
		} else {
			xml = this.sysService.findUsers(Long.valueOf(depId));
		}
		
		try {
			PrintWriter out = response.getWriter();
			out.println(xml);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void bindEntity(ActionForm form, Object obj) {
		super.bindEntity(form, obj);
	}
	
	@Override
	protected void doSaveEntity(ActionForm form, HttpServletRequest request,
			ProcessDefinition object) {		
		//((Users)request.getSession().getAttribute(Globals.SESSION_USER)).getId()
		object.setCreator(null);
		object.setModifyDate(new Date());
		if(object.getId() == null) {
			object.setCreateDate(new Date());
			object.setId(IDGeneratorUtil.generateLongID());
		}
		if(object.getPreId() == null) object.setVersion(1);
		
		String imageData = ((LazyValidatorForm)form).get("processImage").toString();
		String realPath = request.getSession().getServletContext().getRealPath(File.separator);
		realPath = request.getRealPath("/");
		String endStr = File.separator;
		if(realPath.endsWith("/") || realPath.endsWith("\\")) {
			endStr = "";
		}
		String fileName = realPath + endStr + "uploads/flowImages/" + object.getName() + ".png";
		this.buildProcessImagePath(imageData, fileName);
		object.setProcessImagePath("/uploads/flowImages/" + object.getName() + ".png");
		
		//super.doSaveEntity(form, request, object);
		processDefinitionDao.save(object);
	}

	@Override
	public ActionForward save(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		//super.save(mapping, form,request, response);
		ProcessDefinition p = new ProcessDefinition();
		bindEntity(form, p);
		doSaveEntity(form, request, p);
		
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.print("<script language=\"javascript\">");
			pw.print("window.opener.location.href='"+request.getContextPath()+"/ProcessDefinitionAction.do?method=list';window.close();");
			pw.print("</script>");
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		
		return null;
	}

	
}


